<template>
	<el-dialog :visible.sync="visible" :title="!dataForm.id ? $t('add') : editStatus ? '查看' : $t('update')"
		:close-on-click-modal="false" :close-on-press-escape="false" @close="close">
		<el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()"
			label-width="120px">
			<el-form-item prop="name" label="门配置名称">
				<el-input v-model="dataForm.name" :readonly="editStatus" placeholder="请输入门配置名称"></el-input>
			</el-form-item>
			<!-- <el-form-item prop="lineId" label="所属线路">
				<el-select v-model="dataForm.lineId" :disabled="editStatus" placeholder="请选择" @change="changeLine">
					<el-option v-for="item in options1" :key="item.lineId" :label="item.lineName" :value="item.lineId">
					</el-option>
				</el-select>
			</el-form-item> -->
			<!-- <el-form-item prop="stationId" label="站台名称">
				<el-select v-model="dataForm.stationId" :disabled="editStatus||dataForm.lineId==''" placeholder="请选择">
					<el-option v-for="item in options2" :key="item.stationId" :label="item.stationName"
						:value="item.stationId"></el-option>
				</el-select>
			</el-form-item> -->
			<el-form-item prop="doorConfigId" label="门配置文件">
				<el-upload v-if="!editStatus" v-model="dataForm.doorConfigId" accept=".txt" class="upload-demo"
					:headers="headers" :action="url" :before-upload="beforeUpload" :on-preview="handleDownLoad"
					:on-success="handleSuccess" :on-remove="handleRemove" :limit="1" :file-list="fileList"
					style="text-align: left;">
					<el-button size="small" type="primary">点击上传</el-button>
					<!-- <div slot="file" slot-scope="{file}" >
						<span class="el-upload-list__item-actions">
							<span class="el-upload-list__item-delete" @click="handleDownLoad(file)">
									<i class="el-icon-download" />
							</span>
						</span>
					</div> -->

				</el-upload>
				<div v-else>
					<a href="javascript:void(0);"
						@click="downloadFile(dataForm.doorConfig, dataForm.name, 'txt')">{{ dataForm.name + '.txt' }}</a>
				</div>
				<div v-if="!editStatus" class="el-upload__tip">只能上传txt文件，并且只能上传一个文件</div>

			</el-form-item>

			<el-form-item v-if="editStatus" prop="createDate" label="登记日期">
				<el-input v-model="dataForm.createDate" readonly placeholder="请输入线路名称"></el-input>
			</el-form-item>
			<el-form-item v-if="editStatus" prop="sysUserName" label="登记人">
				<el-input v-model="dataForm.sysUserName" readonly placeholder="请输入登记人"></el-input>
			</el-form-item>
		</el-form>
		<template slot="footer">
			<el-button v-if="!editStatus" @click="visible = false">{{ $t('cancel') }}</el-button>
			<el-button v-if="!editStatus" type="primary" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
		</template>
	</el-dialog>
</template>

<script>
import debounce from 'lodash/debounce'
import Cookies from 'js-cookie'
export default {
	data() {
		return {
			visible: false,
			editStatus: false,
			dataForm: {
				id: '',
				name: '',
				// lineId: '',
				// stationId: '',
				doorConfigId: '',
				doorConfig: ''
			},
			timeStatus: false,
			headers: {
				'Authorization': Cookies.get('token')
			},
			fileList: [],
			url: window.SITE_CONFIG['apiURL'] + '/psc/doorconfig/Uploader',
			options1: [],
			options2: [],
		}
	},
	computed: {
		dataRule() {
			return {
				name: [{
					required: true,
					message: '门配置名称不能为空',
					trigger: 'blur'
				}],
				// lineId: [{
				// 	required: true,
				// 	message: '所属线路不能为空',
				// 	trigger: 'blur'
				// }],
				// stationId: [{
				// 	required: true,
				// 	message: '站台名称不能为空',
				// 	trigger: 'blur'
				// }],
				doorConfigId: [{
					required: true,
					message: '门配置文件不能为空',
					trigger: 'blur'
				}],
			}
		}
	},
	mounted() {
		this.getLineId();
		this.getStationName();
	},
	methods: {
		init(status) {
			this.visible = true
			this.fileList = []
			if (status) {
				this.editStatus = status
			} else {
				this.editStatus = false
			}
			this.$nextTick(() => {

				this.$refs['dataForm'].resetFields()
				if (this.dataForm.id) {
					this.getInfo()
					this.getStaionInfo()
				}
			})
		},
		getLineId() {
			this.$http.get('/psc/line/list').then((res) => {
				this.options1 = res.data.data
			})
		},
		getStationName() {
			this.$http.get('/psc/station/list').then((res) => {
				this.options2 = res.data.data
			})
		},
		changeLine() {
			this.$http.get(`/psc/station/sortList/${this.dataForm.lineId}`).then((res) => {
				this.options2 = res.data.data
			})
		},
		//获取所有站点的信息
		getStaionInfo() {
			this.$http.get(`/psc/station/sortList/${this.dataForm.id}`).then(res => {
				this.stationList = res.data.data
				this.timeStatus = true
			})
		},
		beforeUpload(file) {
			const isRightFile =
				file.type === "text/plain"
			if (!isRightFile) {
				this.$message.error("上传文件格式错误!");
				return false;
			}
			if (this.fileList.length == 1) {
				this.$message.error("只能上传一个文件,请将上传的文件删除,再上传!");
				return false;
			}
		},
		//文件上传成功
		handleSuccess(res, file, fileList) {
			if (res.code == 0) {
				this.dataForm.doorConfigId = res.data
			}
		},
		close() {
			this.fileList = []
		},
		//文件下载
		handleDownLoad(file) {
			if (file.response) {
				const name = file.name.split('.txt')
				this.$http.get(`/psc/doorconfig/${file.response.data}`).then(res => {
					this.downloadFile(res.data.data.doorConfig, name[0], '.txt')
				})
			} else {
				this.downloadFile(file.doorConfig, file.doorName, '.txt')
			}
		},
		//移除门的配置
		handleRemove() {
			this.fileList = []
			this.dataForm.doorConfigId = ''
		},
		// 获取信息
		getInfo() {
			this.fileList = []
			this.$http.get(`/psc/doorconfig/${this.dataForm.id}`).then(({
				data: res
			}) => {
				if (res.code !== 0) {
					return this.$message.error(res.msg)
				}
				this.dataForm = {
					...this.dataForm,
					...res.data
				}
				var obj = {
					name: res.data.name + '.txt',
					doorConfig: res.data.doorConfig,
					doorName: res.data.name
				}
				this.fileList.push(obj)
			}).catch(() => { })
		},
		// 表单提交
		dataFormSubmitHandle: debounce(function () {
			this.$refs['dataForm'].validate((valid) => {
				if (!valid) {
					return false
				}
				var obj = {
					id: this.dataForm.id,
					name: this.dataForm.name,
					// lineId:this.dataForm.lineId,
					// stationId: this.dataForm.stationId,
					doorConfig: this.dataForm.doorConfigId == 0 ? this.dataForm.doorConfig : '',
					doorConfigId: this.dataForm.doorConfigId
				}
				this.$http[!this.dataForm.id ? 'post' : 'put']('/psc/doorconfig', obj).then(({
					data: res
				}) => {
					if (res.code !== 0) {
						return this.$message.error(res.msg)
					}
					this.$message({
						message: this.$t('prompt.success'),
						type: 'success',
						duration: 500,
						onClose: () => {
							this.visible = false
							this.$emit('refreshDataList')
						}
					})
				}).catch(() => { })
			})
		}, 1000, {
			'leading': true,
			'trailing': false
		}),
		base64ToBlob(urlData, type) {
			let arr = urlData.split(',');
			let array = arr[0].match(/:(.*?);/);
			let mime = (array && array.length > 1 ? array[1] : type) || type;
			// 去掉url的头，并转化为byte
			let bytes = window.atob(arr[1]);
			// 处理异常,将ascii码小于0的转换为大于0
			let ab = new ArrayBuffer(bytes.length);
			// 生成视图（直接针对内存）：8位无符号整数，长度1个字节
			let ia = new Uint8Array(ab);
			for (let i = 0; i < bytes.length; i++) {
				ia[i] = bytes.charCodeAt(i);
			}
			return new Blob([ab], {
				type: mime
			});
		},
		downloadExportFile(blob, fileName, fileType) {
			let downloadElement = document.createElement('a');
			let href = blob;
			if (typeof blob == 'string') {
				downloadElement.target = '_blank';
			} else {
				href = window.URL.createObjectURL(blob); //创建下载的链接
			}
			downloadElement.href = href;
			downloadElement.download = fileName + '.' + fileType; //下载后文件名
			document.body.appendChild(downloadElement);
			downloadElement.click(); //触发点击下载
			document.body.removeChild(downloadElement); //下载完成移除元素
			if (typeof blob != 'string') {
				window.URL.revokeObjectURL(href); //释放掉blob对象
			}
		},

		/**
		 * desc: base64转文件并下载
		 * @param base64 {String} : base64数据
		 * @param fileType {String} : 要导出的文件类型png,pdf,doc,mp3等
		 * @param fileName {String} : 文件名
		 */
		downloadFile(base64, fileName, fileType) {
			let typeHeader = 'data:application/' + fileType + ';base64,' // 定义base64 头部文件类型
			let converedBase64 = typeHeader + base64;  // 拼接最终的base64
			let blob = this.base64ToBlob(converedBase64, fileType)  // 转成blob对象
			this.downloadExportFile(blob, fileName, fileType) // 下载文件
		}
	}
}
</script>
<style scoped>
.stationList>>>.el-step__icon-inner {
	opacity: 0;
}

.stationList>>>.el-step.is-vertical .el-step__main {
	display: flex;
	align-items: center;
}

.stationList>>>.el-step.is-vertical .el-step__title {
	line-height: auto;
	padding-bottom: 0px;
}

.stationList>>>.el-step:last-of-type .el-step__line {
	display: block;
}
</style>
